package com.sharing.library.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sharing.library.entity.Review;
import com.sharing.library.entity.User;
import com.sharing.library.entity.VO.ReviewVO;
import com.sharing.library.repository.ReviewRepository;
import com.sharing.library.repository.UserRepository;
import com.zhx.framework.util.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanghaixuan
 * @create 2018/3/17-下午2:03
 **/
@RestController
@RequestMapping("/review")
@Api(description="评论管理")
public class ReviewController {
    @Autowired
    private ReviewRepository reviewRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ObjectMapper objectMapper;

    //发表评论
    @PostMapping("/saveReview")
    @ApiOperation(value="提交评论", notes="提交评论")
    public Result saveReview(@RequestBody Review review){

        review.setCreateTime(System.currentTimeMillis());
        Review save = reviewRepository.save(review);

        return Result.OK("",save);
    }


    //获取一个书的全部评论
    @PostMapping("/getReviewList")
    @ApiOperation(value="获取全部评论", notes="获取全部评论")
    public Result getReviewList(@RequestParam Long bookId){
        List<Review> byBookId = reviewRepository.getByBookId(bookId);

        List<ReviewVO> list = new ArrayList<>();

        for(Review review:byBookId){
            ReviewVO reviewVO = objectMapper.convertValue(review, ReviewVO.class);

            User one = userRepository.findOne(reviewVO.getUserId());

            if(one != null){
                reviewVO.setUserName(one.getUsername());
                reviewVO.setHeadImage(one.getHeadImage());
            }

            list.add(reviewVO);

        }

        return  Result.OK("",list);
    }


}
